package juc.demo3;

import java.util.Random;
import java.util.concurrent.*;

public class ExecutorsDemo {

    public static void main(String[] args) {

        //创建一个定长线程池，支持定时及周期性任务执行。
        ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
        ScheduledFuture<Integer> result = null;

        try {
            for (int i = 1; i <= 15; i++) {
                result = service.schedule(() -> {
                    System.out.print(Thread.currentThread().getName());
                    return new Random().nextInt((10));
                }, 2, TimeUnit.SECONDS);
                System.out.println("   *********result:" + result.get());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            service.shutdown();
        }

    }

    public static void testThreadPool() {
        //创建一个定长线程池，可控制线程最大并发数，超出的线程会在队列中等待。
        ExecutorService service = Executors.newFixedThreadPool(5);
        //创建一个单线程化的线程池，它只会用唯一的工作线程来执行任务，
        // 保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
//        ExecutorService service1 = Executors.newSingleThreadExecutor(); // 一个线程
        Future<Integer> result = null;

        try {

            for (int i = 1; i <= 15; i++) {

                result = service.submit(() -> {
                    System.out.print(Thread.currentThread().getName());
                    return new Random().nextInt((10));
                });
                System.out.println("   *********result:" + result.get());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            service.shutdown();
        }
    }
}
